<template>
  <view class="dd-container">
    <!-- 顶部导航栏（添加日期选择器） -->
    <view class="dd-header">
      <text class="header-date">{{ formatDate(selectedDate) }}</text>
    </view>

    <!-- 主要内容区 -->
    <scroll-view class="content" scroll-y>
      <!-- 打卡状态卡片 -->
      <view class="check-card">
        <!-- 今日状态提示 -->
        <view class="today-status">
          <text class="status-text">{{ statusText }}</text>
          <view class="status-time-group" v-if="checkInTime || checkOutTime">
            <text class="status-time" v-if="checkInTime">
              上班打卡时间：{{ checkInTime }}
              <text
                class="check-type-tag"
                :class="checkInIsOutside ? 'outside' : 'normal'">
                {{ checkInIsOutside ? "外勤" : "正常" }}
              </text>
            </text>
            <text class="status-time" v-if="checkOutTime">
              下班打卡时间：{{ checkOutTime }}
              <text
                class="check-type-tag"
                :class="checkOutIsOutside ? 'outside' : 'normal'">
                {{ checkOutIsOutside ? "外勤" : "正常" }}
              </text>
            </text>
          </view>
        </view>

        <!-- 地图区域（仅当前日期显示） -->
        <view class="map-wrapper" v-if="isToday">
          <map
            class="dd-map"
            provider="amap"
            :latitude="centerLatitude"
            :longitude="centerLongitude"
            :markers="markers"
            :scale="16"
            show-location></map>
          <view class="map-label">
            <text class="label-text">
              {{ currentAddress || "获取位置中..." }}
            </text>
          </view>
        </view>

        <!-- 打卡点信息（仅当前日期显示） -->
        <view class="check-point-info" v-if="isToday">
          <text class="point-name">打卡点：{{ checkInPoint.name }}</text>
          <text class="distance">
            距离 {{ distance ? distance.toFixed(1) + "米" : "计算中" }}
            <text class="range">({{ checkInRange }}米内正常打卡)</text>
          </text>
        </view>

        <!-- 打卡按钮组（仅当前日期显示且未完成打卡） -->
        <view
          class="check-btn-group"
          v-if="isToday && (!hasCheckedIn || !hasCheckedOut)">
          <button
            class="check-btn"
            :class="{
              disabled: hasCheckedIn,
              outside: isOutside && !hasCheckedIn,
            }"
            :disabled="hasCheckedIn"
            @click="handleCheckIn('in')">
            {{
              hasCheckedIn
                ? "已上班打卡"
                : isOutside
                ? "外勤上班打卡"
                : "上班打卡"
            }}
          </button>
          <button
            class="check-btn"
            :class="{
              disabled: hasCheckedOut || !hasCheckedIn,
              outside: isOutside && !hasCheckedOut,
            }"
            :disabled="hasCheckedOut || !hasCheckedIn"
            @click="handleCheckIn('out')">
            {{
              hasCheckedOut
                ? "已下班打卡"
                : isOutside
                ? "外勤下班打卡"
                : "下班打卡"
            }}
          </button>
        </view>
      </view>

      <!-- 快捷操作区 -->
      <view class="quick-actions">
        <view class="action-item" @click="showHistory">
          <image src="/static/dd-icon-clock.png" mode="aspectFit"></image>
          <text class="action-text">打卡记录</text>
        </view>
        <view class="action-item" @click="showRules">
          <image src="/static/dd-icon-file.png" mode="aspectFit"></image>
          <text class="action-text">考勤规则</text>
        </view>
        <view class="action-item" @click="showHelp">
          <image src="/static/dd-icon-help.png" mode="aspectFit"></image>
          <text class="action-text">帮助中心</text>
        </view>
      </view>

      <!-- 打卡记录列表 -->
      <view class="record-section">
        <text class="section-title">
          {{
            selectedDate === todayDate
              ? "今日打卡记录"
              : `${formatDate(selectedDate)}打卡记录`
          }}
        </text>
        <view class="record-list" v-if="selectedDateRecords.length > 0">
          <view
            class="record-item"
            v-for="(item, index) in selectedDateRecords"
            :key="index">
            <view class="action-record">
              <text class="record-date">{{ item.date }}</text>
            </view>
            <view class="action-record">
              <text
                class="record-type"
                :class="item.isOutside ? 'outside' : 'normal'">
                {{ item.isOutside ? "外勤" : "正常" }}
                {{ item.checkType === "in" ? "上班" : "下班" }}
              </text>
            </view>
            <view class="action-record">
              <text class="record-time">{{ item.time }}</text>
            </view>
            <view class="action-record">
              <text
                class="update-btn"
                type="text"
                @click="handleUpdate(item.checkType, index)">
                更新
              </text>
            </view>
          </view>
        </view>
        <view class="no-record" v-else>暂无打卡记录</view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 日期相关
      todayDate: new Date().toISOString().split("T")[0],
      selectedDate: new Date().toISOString().split("T")[0],
      isToday: true,

      // 打卡点配置
      checkInPoint: {
        name: "西安总部办公室",
        latitude: 34.19097,
        longitude: 108.881817,
      },
      checkInRange: 500, // 正常打卡范围

      // 地图与定位
      centerLatitude: 34.19097,
      centerLongitude: 108.881817,
      currentLocation: null,
      currentAddress: "",
      markers: [],
      distance: null,
      isOutside: false, // 是否在打卡范围外（外勤）

      // 打卡状态
      hasCheckedIn: false, // 上班已打卡
      hasCheckedOut: false, // 下班已打卡
      checkInTime: "", // 上班打卡时间
      checkOutTime: "", // 下班打卡时间
      checkInIsOutside: false, // 上班是否外勤
      checkOutIsOutside: false, // 下班是否外勤
      statusText: "今日未打卡",

      // 记录相关
      allRecords: [], // 所有打卡记录
      selectedDateRecords: [], // 选中日期的打卡记录
      amapKey: "159f8272893d4c95a0fa850d11aad0ca",
      // amapKey: "1c411f1f83a6220c4cf36d4d860258b4",
    };
  },

  onLoad() {
    this.initDate();
    // this.initMarkers();
    this.loadAllRecords();
    this.checkSelectedDateStatus();
    if (this.isToday) {
      this.getLocation();
    }
  },

  methods: {
    // 初始化日期格式
    initDate() {
      this.isToday = this.selectedDate === this.todayDate;
    },

    // 格式化日期显示（含星期）
    formatDate(dateStr) {
      const date = new Date(dateStr);
      const week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${
        week[date.getDay()]
      }`;
    },

    // 获取当前位置
    getLocation() {
      uni.getLocation({
        type: "gcj02",
        timeout: 15000,
        maximumAge: 0,
        success: (res) => {
          this.currentLocation = res;
          this.centerLatitude = res.latitude;
          this.centerLongitude = res.longitude;
          this.addCurrentMarker();
          this.calculateDistance();
          this.getAddress(res.latitude, res.longitude);
        },
        fail: (err) => {
          this.currentAddress = "定位失败，请检查权限";
          console.error("定位失败：", err);
        },
      });
    },

    // 添加当前位置标记
    addCurrentMarker() {
      this.markers.push({
        id: 2,
        latitude: this.currentLocation.latitude,
        longitude: this.currentLocation.longitude,
        iconPath: "/static/dd-icon-current.png",
        title: "当前位置",
        width: 24,
        height: 24,
        color: "#00B42A",
      });
    },

    // 计算距离并判断是否外勤
    calculateDistance() {
      const R = 6371000;
      const lat1 = this.currentLocation.latitude;
      const lon1 = this.currentLocation.longitude;
      const lat2 = this.checkInPoint.latitude;
      const lon2 = this.checkInPoint.longitude;

      const radLat1 = (lat1 * Math.PI) / 180;
      const radLat2 = (lat2 * Math.PI) / 180;
      const deltaLat = ((lat2 - lat1) * Math.PI) / 180;
      const deltaLon = ((lon2 - lon1) * Math.PI) / 180;

      const a =
        Math.sin(deltaLat / 2) ** 2 +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.sin(deltaLon / 2) ** 2;
      this.distance = R * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
      this.isOutside = this.distance > this.checkInRange;
    },

    // 获取地址
    getAddress(lat, lng) {
      if (!this.amapKey) {
        this.currentAddress = "未配置地址转换Key";
        return;
      }
      uni.request({
        url: `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${this.amapKey}`,
        success: (res) => {
          if (res.data.status === "1") {
            this.currentAddress = res.data.regeocode.formatted_address;
          } else {
            this.currentAddress = "地址获取失败";
          }
        },
        fail: () => {
          this.currentAddress = "地址获取失败";
        },
      });
    },

    // 加载所有打卡记录
    loadAllRecords() {
      this.allRecords = uni.getStorageSync("ddCheckInRecords") || [];
    },

    // 检查选中日期的打卡状态
    checkSelectedDateStatus() {
      this.loadAllRecords();
      // 筛选选中日期的记录
      this.selectedDateRecords = this.allRecords.filter(
        (item) => item.date === this.selectedDate
      );

      // 重置状态
      this.hasCheckedIn = false;
      this.hasCheckedOut = false;
      this.checkInTime = "";
      this.checkOutTime = "";
      this.checkInIsOutside = false;
      this.checkOutIsOutside = false;

      // 处理选中日期的打卡记录
      const inRecord = this.selectedDateRecords.find(
        (item) => item.checkType === "in"
      );
      const outRecord = this.selectedDateRecords.find(
        (item) => item.checkType === "out"
      );

      if (inRecord) {
        this.hasCheckedIn = true;
        this.checkInTime = inRecord.time;
        this.checkInIsOutside = inRecord.isOutside;
      }

      if (outRecord) {
        this.hasCheckedOut = true;
        this.checkOutTime = outRecord.time;
        this.checkOutIsOutside = outRecord.isOutside;
      }

      // 更新状态文本
      if (this.hasCheckedIn && this.hasCheckedOut) {
        this.statusText = "今日已完成上下班打卡";
      } else if (this.hasCheckedIn) {
        this.statusText = "今日已上班打卡，未下班打卡";
      } else if (this.hasCheckedOut) {
        this.statusText = "今日未上班打卡，已下班打卡";
      } else {
        this.statusText = this.isToday ? "今日未打卡" : "该日期无打卡记录";
      }
    },

    // 处理打卡（in=上班，out=下班）
    handleCheckIn(type) {
      const now = new Date();
      const timeStr = `${now.getHours().toString().padStart(2, "0")}:${now
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
      const dateStr = this.selectedDate;

      const newRecord = {
        date: dateStr,
        time: timeStr,
        checkType: type,
        isOutside: this.isOutside,
        address: this.currentAddress,
        distance: this.distance ? this.distance.toFixed(1) : "未知",
      };

      this.allRecords.unshift(newRecord);
      uni.setStorageSync("ddCheckInRecords", this.allRecords);

      // 更新状态
      if (type === "in") {
        this.hasCheckedIn = true;
        this.checkInTime = timeStr;
        this.checkInIsOutside = this.isOutside;
        this.statusText = "今日已上班打卡，未下班打卡";
        uni.showToast({
          title: this.isOutside ? "外勤上班打卡成功" : "上班打卡成功",
          icon: "success",
          duration: 1500,
        });
      } else {
        this.hasCheckedOut = true;
        this.checkOutTime = timeStr;
        this.checkOutIsOutside = this.isOutside;
        this.statusText = "今日已完成上下班打卡";
        uni.showToast({
          title: this.isOutside ? "外勤下班打卡成功" : "下班打卡成功",
          icon: "success",
          duration: 1500,
        });
      }

      // 刷新选中日期的记录
      this.checkSelectedDateStatus();
    },

    // 处理更新打卡
    handleUpdate(type, index = -1) {
      uni.showModal({
        title: "提示",
        content: `是否更新${type === "in" ? "上班" : "下班"}打卡记录？`,
        success: (res) => {
          if (res.confirm) {
            this.updateCheckIn(type, index);
          }
        },
      });
    },

    // 更新打卡记录
    updateCheckIn(type, recordIndex) {
      const now = new Date();
      const timeStr = `${now.getHours().toString().padStart(2, "0")}:${now
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
      const dateStr = this.selectedDate;

      const updatedRecord = {
        date: dateStr,
        time: timeStr,
        checkType: type,
        isOutside: this.isOutside,
        address: this.currentAddress,
        distance: this.distance ? this.distance.toFixed(1) : "未知",
      };

      if (recordIndex > -1) {
        this.allRecords.splice(recordIndex, 1, updatedRecord);
      } else {
        const index = this.allRecords.findIndex(
          (item) => item.date === dateStr && item.checkType === type
        );
        if (index > -1) {
          this.allRecords.splice(index, 1, updatedRecord);
        } else {
          this.allRecords.unshift(updatedRecord);
        }
      }
      uni.setStorageSync("ddCheckInRecords", this.allRecords);

      // 更新状态
      if (type === "in") {
        this.checkInTime = timeStr;
        this.checkInIsOutside = this.isOutside;
        this.statusText = this.hasCheckedOut
          ? "今日已完成上下班打卡"
          : "今日已上班打卡，未下班打卡";
        uni.showToast({
          title: this.isOutside ? "外勤上班打卡更新成功" : "上班打卡更新成功",
          icon: "success",
          duration: 1500,
        });
      } else {
        this.checkOutTime = timeStr;
        this.checkOutIsOutside = this.isOutside;
        this.statusText = "今日已完成上下班打卡";
        uni.showToast({
          title: this.isOutside ? "外勤下班打卡更新成功" : "下班打卡更新成功",
          icon: "success",
          duration: 1500,
        });
      }

      // 刷新选中日期的记录
      this.checkSelectedDateStatus();
    },

    // 打卡记录入口
    showHistory() {
      uni.navigateTo({ url: "/pages/history/history" });
    },

    // 考勤规则入口
    showRules() {
      uni.showToast({ title: "考勤规则功能开发中", icon: "none" });
    },

    // 帮助中心入口
    showHelp() {
      uni.showToast({ title: "帮助中心功能开发中", icon: "none" });
    },
  },
};
</script>

<style scoped>
/* 整体容器 */
.dd-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航栏 */
.dd-header {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  text-align: center;
}

.header-date {
  font-size: 32rpx;
  color: #333;
}

/* 内容区 */
.content {
  width: 100%;
  min-height: calc(100vh - 140rpx);
  padding-bottom: 30rpx;
}

/* 打卡卡片 */
.check-card {
  margin: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

/* 今日状态 */
.today-status {
  padding: 15rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.status-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.status-time-group {
  margin-top: 10rpx;
}

.status-time {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #666;
  margin-top: 8rpx;
}

.check-type-tag {
  margin-left: 15rpx;
  padding: 2rpx 10rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
}

.check-type-tag.normal {
  background-color: #e6f7ee;
  color: #00b42a;
}

.check-type-tag.outside {
  background-color: #fff8e6;
  color: #ff7d00;
}

.update-btn {
  margin-left: 20rpx;
  /* padding: 6rpx 16rpx; */
  font-size: 24rpx;
  border-radius: 8rpx;
  color: #1677ff;
}

/* 地图容器 */
.map-wrapper {
  position: relative;
  margin: 20rpx 0;
  height: 300rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.dd-map {
  width: 100%;
  height: 100%;
}

/* 地图标签 */
.map-label {
  position: absolute;
  bottom: 10rpx;
  left: 0;
  right: 0;
  padding: 8rpx 15rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 26rpx;
  text-align: center;
  margin: 0 10rpx;
  border-radius: 6rpx;
}

/* 打卡点信息 */
.check-point-info {
  padding: 15rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.point-name {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.distance {
  font-size: 26rpx;
  color: #666;
}

.range {
  color: #999;
  font-size: 24rpx;
}

/* 打卡按钮组 */
.check-btn-group {
  display: flex;
  gap: 20rpx;
  margin-top: 25rpx;
}

.check-btn {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 8rpx;
  color: #fff;
}

.check-btn.normal {
  background-color: #1677ff;
}

.check-btn.outside {
  background-color: #ff7d00;
}

.check-btn.disabled {
  background-color: #ccc;
}

/* 快捷操作区 */
.quick-actions {
  display: flex;
  justify-content: space-around;
  margin: 20rpx;
  padding: 25rpx 0;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.action-item image {
  width: 40rpx;
  height: 40rpx;
}

.action-text {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}

/* 打卡记录区域 */
.record-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.section-title {
  display: block;
  padding: 20rpx 25rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
}

.record-list {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10rpx 0;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18rpx 25rpx;
  border-bottom: 1px solid #f5f5f5;
}
.action-record {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-item:last-child {
  border-bottom: none;
}

.record-date {
  font-size: 26rpx;
  color: #333;
}

.record-type {
  padding: 3rpx 12rpx;
  border-radius: 15rpx;
  font-size: 22rpx;
}

.record-type.normal {
  background-color: #e6f7ee;
  color: #00b42a;
}

.record-type.outside {
  background-color: #fff8e6;
  color: #ff7d00;
}

.record-time {
  font-size: 26rpx;
  color: #666;
}

.no-record {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 26rpx;
}
</style>
